package com.fowo.api.sys.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fowo.api.common.model.R;
import com.fowo.api.sys.entity.SysMessage;
import com.fowo.api.sys.model.SysMessageItemVo;
import com.fowo.api.sys.model.SysMessageSearch;
import com.fowo.api.sys.service.SysMessageService;
import com.fowo.api.user.model.JwtUserInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Tag(name = "系统消息")
@RestController
@RequestMapping("/api/sys/message")
public class SysMessageController {
    @Resource
    private SysMessageService sysMessageService;

    @Operation(summary = "获取当前用户未读消息数量")
    @GetMapping("unread-count")
    public R<Long> getUnreadCount(JwtUserInfo jwtUserInfo) {
        if (jwtUserInfo == null) {
            return R.fail("用户未登录！", 0L);
        }
        return R.data(() -> sysMessageService.getUnreadCount(jwtUserInfo.getUserId()));
    }

    @Operation(summary = "设置当前用户已读消息")
    @PutMapping("read")
    public R updateRead(@RequestBody List<Long> messageIds, JwtUserInfo jwtUserInfo) {
        return R.run(() -> sysMessageService.updateRead(jwtUserInfo.getUserId(), messageIds));
    }

    @Operation(summary = "获取发送给当前用户的消息")
    @GetMapping("page")
    public R<Page<SysMessageItemVo>> page(SysMessageSearch search, JwtUserInfo jwtUserInfo) {
        if (jwtUserInfo == null) {
            return R.fail("用户未登录！");
        }
        search.setToUserId(jwtUserInfo.getUserId());
        return R.data(() -> sysMessageService.searchPage(search));
    }

    @Operation(summary = "删除已读")
    @DeleteMapping("read")
    public R deleteRead(JwtUserInfo jwtUserInfo) {
        if (jwtUserInfo == null) {
            return R.fail("用户未登录！");
        }
        return R.ok(() -> sysMessageService.deleteRead(jwtUserInfo.getUserId()));
    }
}
